package com.cungmua.app.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.cungmua.app.R;
import com.cungmua.app.base.BaseAuthenticatedActivity;
import com.cungmua.app.handler.RequestCityHandler;
import com.cungmua.app.handler.RequestDistrictHandler;
import com.cungmua.app.handler.RequestWardHandler;
import com.cungmua.app.model.City;
import com.cungmua.app.model.District;
import com.cungmua.app.model.ShippingAddress;
import com.cungmua.app.model.Ward;
import com.cungmua.app.model.request.CityRequest;
import com.cungmua.app.model.request.DistrictRequest;
import com.cungmua.app.model.request.WardRequest;
import com.cungmua.app.model.response.CityResponse;
import com.cungmua.app.model.response.DistrictResponse;
import com.cungmua.app.model.response.WardResponse;
import com.cungmua.app.task.RequestCityTask;
import com.cungmua.app.task.RequestDistrictTask;
import com.cungmua.app.task.RequestWardTask;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kelvin.nguyen on 6/25/14.
 */
public class CreateShippingAddressActivity extends BaseAuthenticatedActivity implements RequestCityHandler, RequestDistrictHandler, RequestWardHandler, View.OnClickListener {

    private EditText txtName;
    private EditText txtPhone;
    private EditText txtHouseNumer;
    private EditText txtBuilding;
    private EditText txtStreetName;
    private Spinner spnCity;
    private Spinner spnDistrict;
    private Spinner spnWard;
//    private Spinner spnAddressType;

    private ImageButton btnAddressHome,btnAddressOffice;

    ShippingAddress address;
    private ArrayAdapter<City> cityAdapter;
    private ArrayAdapter<District> districtAdapter;
    private ArrayAdapter<Ward> wardAdapter;
//    private ArrayAdapter<String> addressTypeAdapter;
    private Button btnConfirm;
    private int addressType=0;


    @Override
    public int getLayoutResource() {
        return R.layout.activity_create_address_shipping_payment;
    }

    @Override
    public void updateView() {
        if (address != null) {
            if (address.getCustomerName() == null)
                txtName.setText(getCurrentUser().getName());
            else
                txtName.setText(address.getCustomerName());

            if (address.getPhone() == null)
                txtPhone.setText(getCurrentUser().getMobile());
            else
                txtPhone.setText(address.getPhone());

            if(address.getStreetName()!=null)
                txtStreetName.setText(address.getStreetName());
            if(address.getHouseNumber()!=null)
                txtHouseNumer.setText(address.getHouseNumber());
            if(address.getBuildingName()!=null)
                txtBuilding.setText(address.getBuildingName());

            getCityData();
        }
    }

    public void getCityData() {
        CityRequest request = new CityRequest(getDeviceId(), getToken());
        request.setCityType(CityRequest.SHIPPING);
        request.setCurrentCity(getCurrentCity().getId());
        RequestCityTask task = new RequestCityTask(this, this);
        task.execute(request);
    }

    public void getDistrictData(int cityId) {
        if (cityId <= 0) {
            spnDistrict.setEnabled(false);
            spnDistrict.setSelection(0);
            return;
        }
        DistrictRequest request = new DistrictRequest(getDeviceId(), getToken());
        request.setCityId(cityId);
        request.setDistrictType(DistrictRequest.SHIPPABLE);
        request.setCurrentCityId(getCurrentCity().getId());

        RequestDistrictTask task = new RequestDistrictTask(this, this);
        task.execute(request);
    }

    public void getWardData(int districtId) {
        if (districtId <= 0) {
            spnWard.setEnabled(false);
            spnWard.setSelection(0);
            return;
        }

        WardRequest request = new WardRequest(getDeviceId(), getToken());
        request.setCurrentCityId(getCurrentCity().getId());
        request.setWardType(WardRequest.SHIPPABLE);
        request.setDistrictId(districtId);
        RequestWardTask task = new RequestWardTask(this, this);
        task.execute(request);
    }

    @Override
    public void loadControls(Bundle savedInstanceState) {
        address = (ShippingAddress) getIntent().getExtras().getSerializable(SHIPPING_ADDRESS_KEY);

        txtName = (EditText) findViewById(R.id.txtName);
        txtPhone = (EditText) findViewById(R.id.txtPhone);
        txtStreetName = (EditText) findViewById(R.id.txtStreetName);
        txtHouseNumer = (EditText) findViewById(R.id.txtHouseNumer);
        txtBuilding = (EditText) findViewById(R.id.txtBuilding);
        spnCity = (Spinner) findViewById(R.id.spnCity);
        spnDistrict = (Spinner) findViewById(R.id.spnDistrict);
        spnWard = (Spinner) findViewById(R.id.spnWard);
//        spnAddressType = (Spinner) findViewById(R.id.spnAddressType);
        btnConfirm = (Button) findViewById(R.id.btnConfirm);
        btnAddressHome = (ImageButton) findViewById(R.id.btnAddressHome);
        btnAddressOffice = (ImageButton) findViewById(R.id.btnAddressOffice);

        cityAdapter = new ArrayAdapter<City>(this, android.R.layout.simple_spinner_dropdown_item);
        cityAdapter.add(defaultCity());

        districtAdapter = new ArrayAdapter<District>(this, android.R.layout.simple_spinner_dropdown_item);
        districtAdapter.add(defaultDistrict());

        wardAdapter = new ArrayAdapter<Ward>(this, android.R.layout.simple_spinner_dropdown_item);
        wardAdapter.add(defaultWard());

//        addressTypeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item);

        spnCity.setAdapter(cityAdapter);
        spnDistrict.setAdapter(districtAdapter);
        spnWard.setAdapter(wardAdapter);

//        spnAddressType.setAdapter(addressTypeAdapter);

//        spnAddressType.setSelection(address.getAddressType());

        btnConfirm.setOnClickListener(this);

        spnCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                getDistrictData(cityAdapter.getItem(i).getId());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                getWardData(districtAdapter.getItem(i).getId());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });


        btnAddressHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addressType=0;
               setBackgroudImageButton(true);
            }
        });

        btnAddressOffice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addressType=1;
                setBackgroudImageButton(false);
            }
        });


//        addressTypeAdapter.add(getString(R.string.home));
//        addressTypeAdapter.add(getString(R.string.work));
    }


    public void setBackgroudImageButton(boolean isHome){
        if(isHome) {
            btnAddressHome.setImageResource(R.drawable.btn_home_active);
            btnAddressOffice.setImageResource(R.drawable.btn_company);
        }else{
            btnAddressHome.setImageResource(R.drawable.btn_home);
            btnAddressOffice.setImageResource(R.drawable.btn_company_active);
        }
    }

    @Override
    public void onListCity(CityResponse response) {
        cityAdapter.clear();
        List<City> cityList = response.getData();
        List<City> toRemove = new ArrayList<City>();
        for (City c : cityList) {
            if (c.getId() == -1)
                toRemove.add(c);
        }
        if (toRemove != null)
            cityList.removeAll(toRemove);

        cityList.add(0, defaultCity());

        cityAdapter.addAll(cityList);
        cityAdapter.notifyDataSetChanged();

        int i = getIndexOf(cityAdapter, address.getCityName());

        // create new address, set default city to current city
        if (i < 0) {
            i = 0;

            // find position of current city in cityList
            for (int j = 0; j < cityList.size(); j++) {
                if (cityList.get(j).getId() == getCurrentCity().getId()) {
                    i = j;
                    break;
                }
            }
        }
        spnCity.setSelection(i);
    }

    private int getIndexOf(ArrayAdapter adapter, String name) {
        for (int i = 0; i < adapter.getCount(); i++) {
            if (adapter.getItem(i).toString().equals(name))
                return i;
        }
        return -1;
    }

    @Override
    public void onListDistrict(DistrictResponse response) {
        if (response.getCode() == 0) {
            districtAdapter.clear();
            List<District> districtList = response.getData();

            districtList.add(0, defaultDistrict());

            districtAdapter.addAll(districtList);
            districtAdapter.notifyDataSetChanged();

            int i = getIndexOf(districtAdapter, address.getDistrictName());
            if (i < 0) i = 0;
            spnDistrict.setEnabled(true);
            spnDistrict.setSelection(i);
        } else {
            alert(response.getMessage());
        }
    }

    @Override
    public void onListWard(WardResponse response) {
        wardAdapter.clear();

        List<Ward> wardList = response.getData();

        wardList.add(0, defaultWard());

        wardAdapter.addAll(wardList);
        wardAdapter.notifyDataSetChanged();

        int i = getIndexOf(wardAdapter, address.getWardName());
        if (i < 0) i = 0;
        spnWard.setEnabled(true);
        spnWard.setSelection(i);
    }

    public City defaultCity() {
        City defaultCity = new City();
        defaultCity.setId(0);
        defaultCity.setName(getString(R.string.please_choose_city));

        return defaultCity;
    }

    public District defaultDistrict() {
        District defaultDistrict = new District();
        defaultDistrict.setId(0);
        defaultDistrict.setName(getString(R.string.please_choose_district));

        return defaultDistrict;
    }

    public Ward defaultWard() {
        Ward defaultWard = new Ward();
        defaultWard.setId(0);
        defaultWard.setName(getString(R.string.please_choose_ward));

        return defaultWard;
    }

    public void alert(String alert) {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(alert)
                .setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }

    public boolean validateFields() {
        if (txtName.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_name));
            return false;
        }
        if (txtPhone.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_phone));
            return false;
        }
        if (txtHouseNumer.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_house_number));
            return false;
        }
        if (txtStreetName.getText().toString().isEmpty()) {
            alert(getString(R.string.must_have_street));
            return false;
        }
        if (cityAdapter.getItem(spnCity.getSelectedItemPosition()).getId() <= 0) {
            alert(getString(R.string.must_choose_city));
            return false;
        }
        if (districtAdapter.getItem(spnDistrict.getSelectedItemPosition()).getId() <= 0) {
            alert(getString(R.string.must_choose_district));
            return false;
        }
        if (wardAdapter.getItem(spnWard.getSelectedItemPosition()).getId() <= 0) {
            alert(getString(R.string.must_choose_ward));
            return false;
        }
        if (txtPhone.getText().toString().length() < 10 || txtPhone.getText().toString().length() > 11 ||
                !txtPhone.getText().toString().startsWith("0")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("02") ||
                txtPhone.getText().toString().startsWith("03") || txtPhone.getText().toString().startsWith("04") ||
                txtPhone.getText().toString().startsWith("05") || txtPhone.getText().toString().startsWith("06") ||
                txtPhone.getText().toString().startsWith("07") || txtPhone.getText().toString().startsWith("08")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("09") && txtPhone.getText().toString().length() != 10) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } else if (txtPhone.getText().toString().startsWith("01") && txtPhone.getText().toString().length() != 11) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        } if (!txtPhone.getText().toString().matches("[0-9]+")) {
            alert("Số điện thoại nhập không đúng. Vui lòng nhập lại.");
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        if (!validateFields())
            return;

        address.setCustomerName(txtName.getText().toString());
        address.setPhone(txtPhone.getText().toString());
        address.setHouseNumber(txtHouseNumer.getText().toString());
        address.setStreetName(txtStreetName.getText().toString());
        address.setBuildingName(txtBuilding.getText().toString());
        address.setCityId(cityAdapter.getItem(spnCity.getSelectedItemPosition()).getId());
        address.setDistrictId(districtAdapter.getItem(spnDistrict.getSelectedItemPosition()).getId());
        address.setWardId(wardAdapter.getItem(spnWard.getSelectedItemPosition()).getId());
        address.setAddressType(addressType);
        Intent result = new Intent();
        result.putExtra(SHIPPING_ADDRESS_KEY, address);
        setResult(RESULT_OK, result);
        finish();
    }
}
